<template>
  <el-card>
    <template #header>商品分类</template>

    <div>
      <el-button type="primary" size="mini" @click="dialogVisible = true"
        >添加分类</el-button
      >
      <el-dialog title="添加分类" :visible.sync="dialogVisible" width="40%">
        <div>
          <!-- 添加分类的布局 -->
          <el-form
            :model="cateForm"
            :rules="rules"
            ref="ruleForm"
            label-width="80px"
            class="demo-ruleForm"
            size="mini"
          >
            <el-form-item label="分类名称" prop="cateName">
              <el-input v-model="cateForm.cateName"></el-input>
            </el-form-item>
            <el-form-item label="是否启用">
              <el-switch
                v-model="cateForm.state"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" size="mini"
            >取 消</el-button
          >
          <el-button type="primary" @click="addCate('ruleForm')" size="mini"
            >确 定</el-button
          >
        </span>
      </el-dialog>

      <!-- 1.0 分类的表格布局 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column label="分类名称">
          <template v-slot="{ row }">
            <el-input
              v-model="row.cateName"
              v-if="row.flag"
              size="mini"
            ></el-input>
            <span v-else>{{ row.cateName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否启用">
          <template v-slot="{ row }">
            <el-switch
              v-model="row.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              :disabled="!row.flag"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              :type="row.flag ? 'success' : 'primary'"
              size="mini"
              @click="fn(row)"
              >{{ row.flag ? '完成' : '编辑' }}</el-button
            >
            <el-button type="danger" size="mini" @click="delCate(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 2.0 分页处理 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </el-card>
</template>

<script>
import {
  getGoodsCate,
  addGoodsCate,
  delGoodsCate,
  editGoodsCate
} from '@/api/goods.js'

export default {
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false,
      // 分类数据
      cateForm: {
        cateName: '',
        state: true
      },
      // 分类数据规则对象
      rules: {
        cateName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data, total } = await getGoodsCate({
        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
      // 给请求回来的每一条数据添加一个布尔值
      // data.forEach(item => {
      //   item.flag = false
      // })
      this.tableData = data
      this.total = total
      // ！！！ 使用vue提供的$set方法添加响应式数据
      // $set 在data中声明的对象一般都会被数据劫持，如果在data中return的对象起初没有该属性，后续需要添加，就应该使用该方法
      this.tableData.forEach(item => this.$set(item, 'flag', false))
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getCateList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getCateList()
    },
    // 添加分类
    addCate(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const { code } = await addGoodsCate(this.cateForm)
          // console.log(data)
          if (code === 0) {
            // 重置表单并且关闭卡片重新请求数据
            this.$refs[formName].resetFields()
            this.dialogVisible = false
            this.getCateList()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除分类
    delCate(id) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 删除成功的回调
          const { code, msg } = await delGoodsCate({ id })
          // console.log(data)
          if (code === 0) {
            this.$message.success(msg)
            this.getCateList()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 切换编辑状态
    async fn(row) {
      if (row.flag) {
        const { id, cateName, state } = row
        // 完成
        const { code } = await editGoodsCate({
          id,
          cateName,
          state: Boolean(state)
        })
        if (code === 0) {
          row.flag = !row.flag
        }
      } else {
        // 编辑
        row.flag = !row.flag
      }
    }
  }
}
</script>

<style lang="less" scoped></style>
